package com.example.springbootlinmtest.test;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Properties;
import java.io.InputStream;

public class LoadJarUtil {

    public static void loadExternalJars() {

        Properties prop = new Properties();
        InputStream in = null;

        try {
            // 从classpath路径下读取配置文件
            in = LoadJarUtil.class.getClassLoader().getResourceAsStream("loadjars.properties");
            prop.load(in);
            // 获取jar.directory.path的属性值作为外部JAR包的文件路径
            String jarPath = prop.getProperty("jar.directory.path");
            if (jarPath != null && !jarPath.trim().isEmpty()) {
                File file = new File(jarPath);
                if (file.isDirectory()) {
                    File[] files = file.listFiles((dir, name) -> name.endsWith(".jar"));
                    if (files != null && files.length > 0) {
                        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                        method.setAccessible(true);
                        for (File jarFile : files) {
                            System.out.println("==="+jarFile.getName());
                            URL url = jarFile.toURI().toURL();
                            method.invoke(classLoader, url);
                        }
                    }
                }
            } else {
                throw new RuntimeException("Property 'jar.directory.path' not found or empty in loadjars.properties!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}